//
//  ServerHelper.m
//  server
//
//  Created by Christoph Eßer on 1/11/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "ServerHelper.h"
#import "Located.h"
#import <math.h>

//mean earth radius in meters, see http://en.wikipedia.org/wiki/Earth_radius#Mean_radii
#define EARTH_RADIUS_M 6371009.0

@implementation ServerHelper

+(double) distanceBetweenLat1: (double)lat1 andLon1: (double)lon1 andLat2: (double) lat2 andLon2: (double) lon2 {
    //convert coordinates to radians
    lat1 *= M_PI/180.0;
    lon1 *= M_PI/180.0;
    lat2 *= M_PI/180.0;
    lon2 *= M_PI/180.0;
    
    //calculate difference
    double DLat = lat2 - lat1;
    double DLon = lon2 - lon1;
    
    //now apply haversine formula
    // http://en.wikipedia.org/wiki/Haversine_formula
    double nA = pow ( sin(DLat/2), 2 ) + cos(lat1) * cos(lat2) * pow ( sin(DLon/2), 2 );
    
    double nC = 2 * atan2( sqrt(nA), sqrt( 1 - nA ));
    double nD = EARTH_RADIUS_M * nC;
    
    return nD; // Return our calculated distance 
}

+(double) distanceBetween: (NSObject <Located>*) p1 and: (NSObject<Located> *) p2 {    
    return [self distanceBetweenLat1: [p1 latitude]  andLon1: [p1 longitude] andLat2: [p2 latitude] andLon2: [p2 longitude]];
}

+(double) distanceAccuracyBetween: (NSObject <Located>*) p1 and: (NSObject<Located> *) p2 {
    return [p1 accuracy] + [p2 accuracy];
}    

@end
